import React, { useEffect } from 'react';
import { connect } from 'dva';
import { Form, FormItem, createFormActions, FormEffectHooks } from '@formily/antd';
import { Input } from '@formily/antd-components';
import classNames from 'classnames';
import throttle from 'lodash/throttle';
import has from 'lodash/has';
import get from 'lodash/get';

import styles from '../../styles.less';

const actions = createFormActions();
const { onFieldValueChange$, onFormInputChange$ } = FormEffectHooks;

function ForCard({ dispatch, current }) {
  useEffect(() => {
    // 清空状态
    actions.reset({ validate: false });

    // 剔除holder是冗余的key
    const keys = Object.keys(actions.getFormGraph()).filter(val => val !== '');

    // 遍历，给所有的formItem设置值
    keys.forEach(value => {
      if (has(current, value)) {
        actions.setFieldValue([value], get(current, value));
      }
    });
  }, [current]);

  return (
    <Form
      className={classNames(styles.configForm)}
      actions={actions}
      colon={false}
      effects={({ setFieldState }) => {
        // 只监控人工操作引起的FormItem值变化
        onFormInputChange$().subscribe(
          throttle(
            async () => {
              await actions.validate({ silent: true });
              // actions.getFormState().valid取到的结果是异步的，所以必须用到await actions.validate才能得到精确的结果
              const isValid = actions.getFormState().valid;

              // 校验失败
              if (!isValid) {
                return;
              }

              dispatch({
                type: 'formDesigner/updateNode',
                payload: actions.getFormState().values,
              });
            },
            300,
            { trailing: true, leading: false }
          )
        );

        // 监听：checked时，展示对应的输入框
        onFieldValueChange$('isFormat').subscribe(({ value: checked }) => {
          setFieldState('formatRule.format', state => {
            state.visible = checked;
          });

          setFieldState('formatRule.message', state => {
            state.visible = checked;
          });
        });

        onFieldValueChange$('isPattern').subscribe(({ value: checked }) => {
          setFieldState('patternRule.pattern', state => {
            state.visible = checked;
          });

          setFieldState('patternRule.message', state => {
            state.visible = checked;
          });
        });
      }}
    >
      <FormItem
        label="标题"
        name="label"
        allowClear
        required
        triggerType="onChange"
        component={Input}
        placeholder="无"
      />
    </Form>
  );
}

export default connect(({ formDesigner }) => ({
  current: formDesigner.current,
}))(ForCard);
